package com.yimi.yinhepda.db.dao;

import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.SyncServerDataTaskTable;
import com.yimi.yinhepda.entity.response.SyncServerData;
import com.pda.uce.commom.util.LogUtil;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 000432
 *         基础数据同步表
 */
public class SyncServerDatalTableDao extends BaseDao<SyncServerDataTaskTable, Long> {

  private static final String TAG = SyncServerDatalTableDao.class.getSimpleName();

  public SyncServerDatalTableDao() {
    super(DbHelper.getInstance(BaseApplication.getContext()), SyncServerDataTaskTable.class);
  }

  public void createOrUpdate(List<SyncServerData> list) {
    SQLiteDatabase database = getDbHelper().getWritableDatabase();
    String tableName = dao.getTableName();
    StringBuffer sql = new StringBuffer("replace into ");
    sql.append(tableName);
    sql.append("(sync_task_id,");
    sql.append("sync_task_name,");
    sql.append("table_name,");
    sql.append("id_column_name,");
    sql.append("sync_service_url,");
    sql.append("status,");
    sql.append("latest_time,");
    sql.append("page_size,");
    sql.append("from_type,");
    sql.append("cdstatus)");
    //15
    sql.append("values(?,?,?,?,?,?,?,?,?,?)");
    LogUtil.e("sql=" + sql.toString());

    database.beginTransaction();
    for (SyncServerData item : list) {
      if (item.getCdstatus() != null) {
        if (item.getCdstatus().equals("dept")) {
          item.setCdstatus("all");
        }
      }
      Object[] values = new Object[] {
          item.getSYNC_TASK_ID(), item.getSYNC_TASK_NAME(), item.getTABLE_NAME(), item.getID_COLUMN_NAME(), item.getSYNC_SERVICE_URL(),
          item.getSTATUS(), item.getLatest_time(), item.getPAGE_SIZE(), item.getFROM_TYPE(), item.getCdstatus()
      };
      database.execSQL(sql.toString(), values);
    }
    database.setTransactionSuccessful();
    database.endTransaction();
  }

  /**
   * 根据表名获取需要同步的表
   */
  public SyncServerDataTaskTable getSyncServerData(String tableName) {
    try {
      QueryBuilder<SyncServerDataTaskTable, Long> queryBuilder = dao.queryBuilder();
      Where where = queryBuilder.where();
      where.eq("table_name", tableName);
      //是否同步:0:"不同步";1:"同步"',
      where.and().eq("status", 1);
      where.and().isNotNull("cdstatus");
      List<SyncServerDataTaskTable> list = queryBuilder.query();
      if (list != null && list.size() > 0) {
        return list.get(0);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }
}
